package cn.itsource.basic.controller;

import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.FastDfsUtil;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 1.访问地址
 * 2.参数
 * 3.返回值
 */
@RestController
@RequestMapping("/fastDfs")
@Api(tags = "文件接口",description = "文件上传或删除")
public class FastDfsController {

    /*
    @RequestPart  文件上传必用
    value = "file"  前端传送的文件名
     */
    @PostMapping
    public AjaxResult upload(@RequestPart(required = true,value = "file") MultipartFile file){
        try {
            String filename = file.getOriginalFilename();
            String extName = filename.substring(filename.lastIndexOf(".")+1);
            String path = FastDfsUtil.upload(file.getBytes(), extName);
            return AjaxResult.me().setResultObj(path);//将上传返回的路径返回给前端
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("上传失败！");
        }
    }

    /**
     * @RequestParam 接口地址栏中的参数
     * @param path
     * @return
     */
    @DeleteMapping
    public AjaxResult delete(@RequestParam(required = true,value = "path") String path){
        try {
            String pathTmp = path.substring(1); // goup1/xxxxx/yyyy
            String groupName =  pathTmp.substring(0, pathTmp.indexOf("/")); //goup1
            String remotePath = pathTmp.substring(pathTmp.indexOf("/")+1);//

            FastDfsUtil.delete(groupName, remotePath);
            return AjaxResult.me();//将上传返回的路径返回给前端
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("删除失败！");
        }
    }
}
